using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using wicpowerTcpTool.Models;  // 添加ForwardGroup所在的命名空间

namespace wicpowerTcpTool.Utilities
{
    public static class ConfigManager
    {
        private const string ConfigFileName = "config.ini";

        public static void SaveForwardGroupConfig(System.Net.IPAddress listenIP, int port1, int port2, string remark, string authToken = "")
        {
            try
            {
                var lines = new List<string>();
                
                // 如果文件已存在，读取原有内容
                if (File.Exists(ConfigFileName))
                {
                    lines = File.ReadAllLines(ConfigFileName).ToList();
                }

                // 添加新配置
                lines.Add($"[ForwardGroup_{DateTime.Now:yyyyMMddHHmmss}]");
                lines.Add($"ListenIP={listenIP}");
                lines.Add($"Port1={port1}");
                lines.Add($"Port2={port2}");
                lines.Add($"Remark={remark}");
                if(!string.IsNullOrEmpty(authToken))
                {
                    lines.Add($"AuthToken={authToken}");
                }
                lines.Add("");

                // 写入文件
                File.WriteAllLines(ConfigFileName, lines);
            }
            catch (Exception ex)
            {
                // 记录错误日志
                File.AppendAllText("config_error.log", $"{DateTime.Now}: {ex.Message}\n");
            }
        }

        public static List<Dictionary<string, string>> LoadAllConfigs()
        {
            var configs = new List<Dictionary<string, string>>();
            
            if (!File.Exists(ConfigFileName))
                return configs;

            var lines = File.ReadAllLines(ConfigFileName);
            Dictionary<string, string> currentConfig = null;

            foreach (var line in lines)
            {
                if (line.StartsWith("[") && line.EndsWith("]"))
                {
                    currentConfig = new Dictionary<string, string>();
                    configs.Add(currentConfig);
                }
                else if (currentConfig != null && line.Contains("="))
                {
                    var parts = line.Split(new[] { '=' }, 2);
                    if (parts.Length == 2)
                    {
                        currentConfig[parts[0]] = parts[1];
                    }
                }
            }

            return configs;
        }

        public static ForwardGroup LoadForwardGroupConfig(Dictionary<string, string> config)
        {
            try
            {
                if (!config.ContainsKey("Port1") || !config.ContainsKey("Port2"))
                    return null;

                var listenIP = config.ContainsKey("ListenIP") ? 
                    IPAddress.Parse(config["ListenIP"]) : IPAddress.Any;
                var port1 = int.Parse(config["Port1"]);
                var port2 = int.Parse(config["Port2"]);
                var remark = config.ContainsKey("Remark") ? config["Remark"] : "";
                var authToken = config.ContainsKey("AuthToken") ? config["AuthToken"] : "";

                return new ForwardGroup(0, port1, port2, remark, authToken, listenIP);
            }
            catch
            {
                return null;
            }
        }

        public static IPAddress GetDefaultListenIP()
        {
            try
            {
                var configs = LoadAllConfigs();
                if (configs.Count > 0)
                {
                    var firstConfig = configs.First();
                    if (firstConfig.ContainsKey("ListenIP"))
                    {
                        return IPAddress.Parse(firstConfig["ListenIP"]);
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static bool RemoveForwardGroupConfig(int port1, int port2)
        {
            try
            {
                if (!File.Exists(ConfigFileName))
                    return false;

                var lines = File.ReadAllLines(ConfigFileName).ToList();
                bool inTargetSection = false;
                bool removed = false;
                int sectionStart = -1;

                for (int i = 0; i < lines.Count; i++)
                {
                    if (lines[i].StartsWith("[") && lines[i].EndsWith("]"))
                    {
                        // 新节开始，重置状态
                        inTargetSection = false;
                        sectionStart = i;
                    }
                    else if (lines[i].StartsWith($"Port1={port1}") && 
                             lines[i + 1].StartsWith($"Port2={port2}"))
                    {
                        inTargetSection = true;
                    }

                    // 找到目标节则删除
                    if (inTargetSection && sectionStart >= 0)
                    {
                        // 删除整个节(从sectionStart到下一个节或文件末尾)
                        int removeCount = 1;
                        while (i + removeCount < lines.Count && 
                              !lines[i + removeCount].StartsWith("["))
                        {
                            removeCount++;
                        }
                        lines.RemoveRange(sectionStart, removeCount);
                        removed = true;
                        break;
                    }
                }

                if (removed)
                {
                    File.WriteAllLines(ConfigFileName, lines);
                }
                return removed;
            }
            catch (Exception ex)
            {
                File.AppendAllText("config_error.log", $"{DateTime.Now}: Remove failed - {ex.Message}\n");
                return false;
            }
        }
    }
}
